package com.hoperun.product.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.blankj.utilcode.util.AppUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.common.GlobalState;
import com.hoperun.product.common.Setting;
import com.hoperun.product.common.TableNo;
import com.hoperun.product.entity.LoginEntity;
import com.hoperun.product.entity.SpinnerEntity;
import com.hoperun.product.entity.UserBean;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.MD5Encrypt;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.util.scan.ScanGun;
import com.hoperun.product.util.scan.ScanGun.ScanGunCallBack;
import com.hoperun.product.view.SimpleDialog;

import com.hoperun.yieldmgryue.R;
import com.zhuyu.downloadlibrary.DownloadDialog;
import com.zhuyu.downloadlibrary.UpdateInfoBizData;

public class LoginActivity extends MIP_BaseActivity implements OnClickListener {

	private Button loginBtn;
	private EditText accountEt;
	private EditText passwordEt;
	private Spinner mBmmcSp;
	private TextView versionTv;
	//车间下拉框适配器
	private ArrayAdapter<String> mBmmcSpAdapter;
	//记录存储车间的text值
	private List<String> mBmmcList = new ArrayList<String>();
	//记录车间数据字典
	List<SpinnerEntity> mSpinnerList=new ArrayList<SpinnerEntity>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		initDate();
		initView();
		initEvent();
		selectDict();
		getNewVersion();
	}

	private void initDate() {

		// 初始化列表中第一个数据为“请选择”
				//mBmmcList.add("请选择车间");
		mSpinnerList.add(new SpinnerEntity("请选择车间 \nVui lòng chọn xưởng", ""));
	}

	private void initView() {
		loginBtn = (Button) findViewById(R.id.login_loginBtn);
		accountEt = (EditText) findViewById(R.id.login_accountEt);
		passwordEt = (EditText) findViewById(R.id.login_passwordEt);
		mBmmcSp = (Spinner) findViewById(R.id.login_bmmcSp);
		versionTv=findViewById(R.id.versionTv);
		// 设置车间下拉框适配器 数据来源于访问服务器的数据字典
		mBmmcSpAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, mBmmcList);
		mBmmcSpAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
		mBmmcSp.setAdapter(mBmmcSpAdapter);
		
		accountEt.setFocusable(true);  
		accountEt.setFocusableInTouchMode(true);  
		
		accountEt.requestFocus();
		accountEt.requestFocusFromTouch();
		accountEt.findFocus();

		versionTv.setText("version:"+AppUtils.getAppVersionName());
	}

	
	private void initEvent() {
		loginBtn.setOnClickListener(this);
//		accountEt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//		accountEt.setOnEditorActionListener(new OnEditorActionListener() {
//
//			@Override
//			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//				
//				if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//					//toast(actionId + "");
//					startLoginByScan();
//					return true;
//				}
//
//				return false;
//			}
//		});
		accountEt.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
					//toast(actionId + "");
					startLoginByScan();
				}
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_loginBtn:
			startLogin();
			break;
		}
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		
		Log.e("dispatchKeyEvent", event.getKeyCode() + "");
		// toast("dispatchKeyEvent" + event.getKeyCode() + "");
		// 拦截物理键盘事件
		// if (event.getKeyCode() >= KeyEvent.KEYCODE_0 && event.getKeyCode() !=
		// KeyEvent.KEYCODE_DEL) {
		// if (event.getAction() == KeyEvent.ACTION_DOWN) {
		// mScanGun.isMaybeScanning(event.getKeyCode(), event);
		// return true;
		// }
		// return true;
		// }
		// 拦截回车键，成功解决焦点跳行的问题
//		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//
//			return true;
//		}
		return super.dispatchKeyEvent(event);
	}
	/**
	 * 通过扫描的方式登陆
	 */
	private void startLoginByScan() {

		String account = accountEt.getText().toString().trim();

		String password = MD5Encrypt.MD5(passwordEt.getText().toString().trim());
		
		
		if(TextUtils.isEmpty(password)){
			password=MD5Encrypt.MD5("abc123");
		}
		
		
		String bmmc="";
		//车间不是必选项
		int position =mBmmcSp.getSelectedItemPosition();
		if(position<0){
			SimpleDialog.show(this, "登录失败，服务器连接异常！\nĐăng nhập thất bại, liên kết máy bất thường");
			return;
		}
			bmmc = mSpinnerList.get(position).fieldValue;
		
		if (TextUtils.isEmpty(account)) {
			toast("请输入工号！");
			return;
		}
		if (TextUtils.isEmpty(password)) {
			toast("请输入密码！");
			return;
		}
		login(account,password,bmmc);
	}
	
	/**
	 * 开始登陆，正常手动输入
	 */
	private void startLogin() {
		//accountEt.setText("admin");
		//passwordEt.setText("abc123");

		String account = accountEt.getText().toString().trim();

		String password = MD5Encrypt.MD5(passwordEt.getText().toString().trim());
		String bmmc="";
		//车间不是必选项
		int position =mBmmcSp.getSelectedItemPosition();
		if(position<0){
			SimpleDialog.show(this, "登录失败，服务器连接异常！");
			return;
		}
			bmmc = mSpinnerList.get(position).fieldValue;
		
		if (TextUtils.isEmpty(account)) {
			toast("请输入工号！");
			return;
		}
		if (TextUtils.isEmpty(password)) {
			toast("请输入密码！");
			return;
		}
		login(account,password,bmmc);
	}
	
	/**
	 * 登录
	 * @param account
	 * @param password
	 * @param bmmc
	 */
	private void login(String account,String password,String bmmc){
		showWait();
		RequestServiceImpl.login(mMIPHandler, IServiceImpl.LOGIN_R, account, password,bmmc);
	}
	
	/**
	 * 获取车间下拉框值
	 */
	private void selectDict() {
		showWait();
		RequestServiceImpl.selectDict(mMIPHandler, IServiceImpl.SELECTDICT, TableNo.BMMC);
	}


	/**
	 * 获取新版本
	 */
	private void getNewVersion() {
		showWait();
		final  String appname="产量app";
		RequestServiceImpl.getNewVersion(mMIPHandler, IServiceImpl.GET_NEW_VERSION,appname);
	}

	@Override
	public void onPostHandle(int requestType, Object objBody, boolean error) {

		stopWait();
		String opt = "";
		String msg = "";
		if (error) {
			switch (requestType) {
				case IServiceImpl.GET_NEW_VERSION:
					try {


						JSONObject jsonObj = new JSONObject((String) objBody);
						opt = jsonObj.optString("OPT_FLAG");
						JSONObject data = jsonObj.optJSONObject("DATA");
						msg = jsonObj.optString("MSG_INFO");
						if ("SUCCESS".equals(opt) && data != null) {
							UpdateInfoBizData bizData = ParseUtils.parse(data.toString(), UpdateInfoBizData.class);
							if (bizData != null) {
								final String url = bizData.getAndroidUrl();
								String version = bizData.getAndroidversionCode();
								String curVersion = AppUtils.getAppVersionName();
								String forceUpdate = bizData.getAndroidForced();
								String filename = url.substring(url.lastIndexOf("/")+1);
								// 文件保存在应用关联缓存目录
								String filePath=this.getExternalFilesDir(null)+"/"+filename;
								if (!curVersion.equals(version)) {

									if ("1".equals(forceUpdate)) {
										SimpleDialog.forceShow(this,"应用有新版本，需强制升级！\nỨng dụng có phiên bản mới, cần phải nâng cấp!", new SimpleDialog.OnPositiveClickListener() {

											@Override
											public void onPositiveClick() {
												DownloadDialog dowDialog = DownloadDialog.newInstance(url,filePath, true);
												dowDialog.setDownloadListener(new DownloadDialog.DownloadSimpleListener() {

													@Override
													public void onSuccess() {
														AppUtils.installApp(filePath);
													}

													@Override
													public void onError() {
														SimpleDialog.show(LoginActivity.this,  "下载失败！\nTải về thất bại!");
													}
												});
												dowDialog.show(getSupportFragmentManager(), "DownLoad");


											}
										});
									} else {
										SimpleDialog.show(this, "应用有新版本，是否立刻升级？\nỨng dụng có phiên bản mới, nâng cấp ngay hay không?", new SimpleDialog.OnNegativeClickListener() {

											@Override
											public void onNegativeClick() {

											}
										}, new SimpleDialog.OnPositiveClickListener() {

											@Override
											public void onPositiveClick() {
												DownloadDialog dowDialog = DownloadDialog.newInstance(url, filePath,false);
												dowDialog.setDownloadListener(new DownloadDialog.DownloadSimpleListener() {

													@Override
													public void onSuccess() {
														AppUtils.installApp(filePath);
													}

													@Override
													public void onError() {
														SimpleDialog.show(LoginActivity.this,"下载失败！\nTải về thất bại!");
													}
												});
												dowDialog.show(getSupportFragmentManager(), "DownLoad");


											}
										});
									}
								}

							}

						} else {
							if (TextUtils.isEmpty(msg)) {
								SimpleDialog.show(this, "没有维护更新配置，请联系管理员！\nKhông có cấu hình cập nhật cần đổi mới, xin liên lạc nhân viên quản lý!");
							} else {
								SimpleDialog.show(this, msg);
							}

						}


					} catch (Exception e) {
						e.printStackTrace();
						toast("数据解析异常! Số liệu phân tích khác thường!" + e.toString());
					}
					break;
			case IServiceImpl.LOGIN_R:
				try {
					// 需注意这里判断登录失败不能去解析json，服务端只会返回单字符串“FALSE”

					if ("FALSE".equals(objBody.toString())) {
						SimpleDialog.show(this, "登陆失败，请检查用户名和密码是否正确！\nĐăng nhập thất bại, vui lòng kiểm tra tên người dùng và mật khẩu ");
						return;
					}

					JSONObject jsonObj = new JSONObject((String) objBody);
					opt = jsonObj.optString("OPT_FLAG");
					if ("SUCCESS".equals(opt)) {

						JSONObject userbeanObj = jsonObj.optJSONObject("userBean");
						// 保存userbean数据到本地，格式为json字符串
						SharedPreUtil.putValue(this, SharedPreUtil.USERBEAN, userbeanObj.toString());

						UserBean userBean = new UserBean();
						userBean = ParseUtils.parse(userbeanObj.toString(), UserBean.class);
						
						
						
						// 保存权限代码
						JSONArray QXCOMMArray = jsonObj.optJSONArray("QXCOMM");
						// 闲置空
						SharedPreUtil.putValue(this, SharedPreUtil.CM0140202, "");
						for (int i = 0; i < QXCOMMArray.length(); i++) {
							JSONObject QXCOMMObj = QXCOMMArray.getJSONObject(i);
							String CM0140202 = QXCOMMObj.optString("CM0140202");
							if (!TextUtils.isEmpty(CM0140202)) {
								SharedPreUtil.putValue(this, SharedPreUtil.CM0140202, CM0140202);
								break;
							}
						}

						String YHM = userBean.XTYHBean.YHM;
						String BMJC = userBean.XTYHBean.BMJC;
						
						if(YHM.contains(BMJC)){
							YHM=YHM.substring(BMJC.length());	
						}
						//改为从文本框中获取用户id
						//去掉所有字母  2017年12月15日修改
						//String YHM =accountEt.getText().toString().trim().replaceAll("[a-zA-Z]","");
						
						
						// 保存YHM 员工工号
						SharedPreUtil.putValue(this, SharedPreUtil.YHM, YHM);
						
						/**********************2017年12月2日，更改bmmc保存数据来源*******************/
						String bmmc=userBean.XTYHBean.BMMC;
						
					/*	String bmmc = mSpinnerList.get(mBmmcSp.getSelectedItemPosition()).fieldText;
						//保存车间名称 是text值
						if(mBmmcSp.getSelectedItemPosition()==0){
							bmmc="";
						}*/
						SharedPreUtil.putValue(this, SharedPreUtil.BMMC, bmmc);
						/*************************结束*********************************/
						
						Intent intent = new Intent(this, MainActivity.class);
						startActivity(intent);
						

						// finish();
					} else {
						SimpleDialog.show(this, "登陆失败，请检查用户名和密码是否正确！Đăng nhập thất bại, vui lòng kiểm tra tên người dùng và mật khẩu");
					}

				} catch (Exception e) {
					e.printStackTrace();
					toast("数据异常\nDữ liệu bất thường");
				}
				break;
			case IServiceImpl.SELECTDICT:

				try {
					Gson gson = new Gson();
					List<SpinnerEntity> spinnerList= gson.fromJson(objBody.toString(), new TypeToken<List<SpinnerEntity>>() {
					}.getType());
					//保存到spinner数据字典中
					mSpinnerList.addAll(spinnerList);
					//保存车间文本值，适配下拉框
					for (SpinnerEntity spinnerEntity : mSpinnerList) {
						mBmmcList.add(spinnerEntity.fieldText);
					}
					//下拉框数据刷新
					mBmmcSpAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();

				}
				break;
			}
		} else {
			switch (requestType) {
			case IServiceImpl.LOGIN_R:
				toast("登陆失败，链接服务器异常！Lỗi đăng nhập, ngoại lệ máy phục vụ liên kết!");
				break;
			case IServiceImpl.SELECTDICT:
				toast("初始化失败，链接服务器异常！Khởi động thất bại, ngoại lệ máy phục vụ!");
				break;
		

			}

		}
	}

}
